package org.dromara.wmscloud.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.wmscloud.domain.vo.BaseLocationVo;
import org.dromara.wmscloud.domain.vo.BaseMatVo;
import org.dromara.wmscloud.domain.vo.BaseWarehouseVo;
import org.dromara.wmscloud.mapper.BaseMatMapper;
import org.springframework.stereotype.Service;
import org.dromara.wmscloud.domain.bo.BaseMatBomBo;
import org.dromara.wmscloud.domain.vo.BaseMatBomVo;
import org.dromara.wmscloud.domain.BaseMatBom;
import org.dromara.wmscloud.mapper.BaseMatBomMapper;
import org.dromara.wmscloud.service.IBaseMatBomService;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 物料BOMService业务层处理
 *
 * @author hou
 * @date 2025-04-05
 */
@RequiredArgsConstructor
@Service
public class BaseMatBomServiceImpl implements IBaseMatBomService {

    private final BaseMatBomMapper baseMapper;
    private final BaseMatMapper baseMatMapper;

    /**
     * 查询物料BOM
     *
     * @param bomId 主键
     * @return 物料BOM
     */
    @Override
    public BaseMatBomVo queryById(Long bomId){
        return baseMapper.selectVoById(bomId);
    }

    /**
     * 分页查询物料BOM列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 物料BOM分页列表
     */
    @Override
    public TableDataInfo<BaseMatBomVo> queryPageList(BaseMatBomBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BaseMatBom> lqw = buildQueryWrapper(bo);
        Page<BaseMatBomVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<BaseMatBomVo> records = result.getRecords();
        if (!records.isEmpty()) {
            fillFatherMatFields(records);
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的物料BOM列表
     *
     * @param bo 查询条件
     * @return 物料BOM列表
     */
    @Override
    public List<BaseMatBomVo> queryList(BaseMatBomBo bo) {
        LambdaQueryWrapper<BaseMatBom> lqw = buildQueryWrapper(bo);
        List<BaseMatBomVo> list = baseMapper.selectVoList(lqw);
        if (!list.isEmpty()) {
            fillFatherMatFields(list);
        }
        return list;
    }

    private LambdaQueryWrapper<BaseMatBom> buildQueryWrapper(BaseMatBomBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BaseMatBom> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(BaseMatBom::getBomId);
        lqw.eq(StringUtils.isNotBlank(bo.getFatherMatCode()), BaseMatBom::getFatherMatCode, bo.getFatherMatCode());
        lqw.eq(StringUtils.isNotBlank(bo.getChildMatCode()), BaseMatBom::getChildMatCode, bo.getChildMatCode());
        return lqw;
    }

    /**
     * 新增物料BOM
     *
     * @param bo 物料BOM
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(BaseMatBomBo bo) {
        BaseMatBom add = MapstructUtils.convert(bo, BaseMatBom.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setBomId(add.getBomId());
        }
        return flag;
    }

    /**
     * 修改物料BOM
     *
     * @param bo 物料BOM
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BaseMatBomBo bo) {
        BaseMatBom update = MapstructUtils.convert(bo, BaseMatBom.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BaseMatBom entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除物料BOM信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 回填父级物料的名称、图号等字段
     */
    private void fillFatherMatFields(List<BaseMatBomVo> records) {
        Set<String> matCodes = records.stream()
            .map(BaseMatBomVo::getFatherMatCode)
            .filter(Objects::nonNull)
            .collect(Collectors.toSet());

        Set<String> childMatCodes = records.stream()
            .map(BaseMatBomVo::getChildMatCode)
            .filter(Objects::nonNull)
            .collect(Collectors.toSet());

        if (matCodes.isEmpty()) {
            return;
        }

        Map<String, BaseMatVo> matVoMap = baseMatMapper.selectBaseMatVoByMatCodes(matCodes).stream()
            .collect(Collectors.toMap(BaseMatVo::getMatCode, Function.identity()));

        Map<String, BaseMatVo> childMatVoMap = baseMatMapper.selectBaseMatVoByMatCodes(childMatCodes).stream()
            .collect(Collectors.toMap(BaseMatVo::getMatCode, Function.identity()));

        records.forEach(vo -> {
            BaseMatVo matVo = matVoMap.get(vo.getFatherMatCode());
            if (matVo != null) {
                vo.setFatherMatName(matVo.getMatName());
                vo.setFigNum(matVo.getFigNum());
            }
        });

        records.forEach(vo -> {
            BaseMatVo matVo = childMatVoMap.get(vo.getChildMatCode());
            if (matVo != null) {
                vo.setChildMatName(matVo.getMatName());
            }
        });
    }
}
